package com.pureut.socket.server;

import com.pureut.socket.config.WebSocketConfig;
import com.pureut.socket.domain.MsgResponseVo;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Author hl
 **/
@Component
@ServerEndpoint(value = "/webSocketToUser/{id}", configurator = WebSocketConfig.class)
public class WebSocketToUser {

    //静态变量，用来记录当前在线连接数。应该把它设计成线程安全的。
    private static int onlineCount = 0;

    private static ConcurrentHashMap<String, WebSocketToUser> webSocketSet = new ConcurrentHashMap<>();
    //与某个客户端的连接会话，需要通过它来给客户端发送数据
    private static Session session;

    //指定的sid，具有唯一性
    private static String sid = "";


    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(@PathParam("id") String id, Session session, EndpointConfig config) throws IOException {
        //获取WebsocketConfig.java中配置的“sessionId”信息值
        String httpSessionId = (String) config.getUserProperties().get("sessionId");
        this.session = session;
        this. sid = id;
        //加入set中
        webSocketSet.put(sid, this);
        //在线数加1
        addOnlineCount();
        MsgResponseVo userMsgResponseVo = new MsgResponseVo();
        userMsgResponseVo.setMsg("SUCCESS");
        sendMessage("SUCCESS");
        System.out.println("用戶" + sid + "加入！当前在线人数为" + getOnlineCount());
    }


    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        //从set中删除
        webSocketSet.remove(this);
        //在线数减1
        subOnlineCount();
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        System.err.println("来自客户端的消息:" + message);
    }

    /**
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        error.printStackTrace();
    }

    /**
     * 实现服务器主动推送
     */
    public void sendMessage(String message) throws IOException {
        session.getBasicRemote().sendText(message);
    }

    /**
     * 向指定用户发送消息(多人的话遍历此方法)
     */
    public boolean sendToUser(String message, String sendUserId) throws IOException {
        if (webSocketSet.get(sendUserId) != null) {
            if (!sid.equals(sendUserId)) {
                return false;
                //webSocketSet.get(sendUserId).sendMessage("用户" + sendUserId + "发来消息：" + message);
            } else {
                webSocketSet.get(sendUserId).sendMessage(message);
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                return true;
            }
        } else {
            //如果用户不在线则返回不在线信息给自己
            return false;
        }
    }

    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
        WebSocketToUser.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        WebSocketToUser.onlineCount--;
    }

}